package cn.fresh.xuanyuan.module.system.convert.handler;

import cn.fresh.xuanyuan.module.system.dal.dataobject.wx.WXTemplateDataDO;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(List.class)
public class TemplateDataToStringTypeHandler implements TypeHandler<List<WXTemplateDataDO>> {
    @Override
    public void setParameter(PreparedStatement ps, int i, List<WXTemplateDataDO> parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, JSON.toJSONString(parameter));
    }

    @Override
    public List<WXTemplateDataDO> getResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return getResult(value);
    }

    @Override
    public List<WXTemplateDataDO> getResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return getResult(value);
    }

    @Override
    public List<WXTemplateDataDO> getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return getResult(value);
    }

    private List<WXTemplateDataDO> getResult(String value) {
        List<WXTemplateDataDO> result = null;
        if (StringUtils.isBlank(value)) {
            return result;
        }
        try {
            result = JSON.parseArray(value, WXTemplateDataDO.class);
        }
        catch (Exception ignored) {}
        return result;
    }
}
